package com.hnkywl.sts.dao.sfgl;

import net.ruixin.orm.hibernate.SimpleHibernateTemplate;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;

/**
 * Created with IntelliJ IDEA.
 * User: ccr
 * Date: 13-7-10
 * Time: 下午3:49
 * To change this template use File | Settings | File Templates.
 */
@Repository
public class SfkglDao extends SimpleHibernateTemplate{
    //返回true可以取消审核  false 不可以
    public Boolean qxshyz(Long sfkId){
        String sql1 = "select id from t_biz_sfk where id = ? and deleted = 0 and jiuqi_insert_flag = 3 and zt = 'ysh'";
        if(existsSQLQuery(sql1,sfkId)){
            throw new RuntimeException("收付款已导入财务系统！");
        }
        String sql2 = "select gsjg.id from t_biz_sfk sfk left join t_sys_gsjg gsjg on sfk.gldw_id = gsjg.id where sfk.id = ? and gsjg.deleted = 0 and gsjg.sfzx = 0 and sfk.zt = 'ysh'";
        if(!existsSQLQuery(sql2,sfkId)){
            throw new RuntimeException("供应商或客户已删除！");
        }
        String sql3 = "select case when khh.id is not null then khh.deleted else 0 end from t_biz_sfk sfk left join t_sys_khh khh on sfk.nbkhh_id = khh.id where sfk.id = ?";
        Integer exist = ((BigDecimal) createSQLQuery(sql3,sfkId).uniqueResult()).intValue();
        if(exist == 1){
            throw new RuntimeException("开户行已注销！");
        }

        String sql4 = "select id from t_biz_pj where sfk_id = ?";
        if(existsSQLQuery(sql4,sfkId)){
            String fk = "select pj.id from t_biz_pj pj left join t_biz_sfk sfk on sfk.id = pj.sfk_id where sfk.id = ? and sfk.sfklx in (1,2) and pj.status in (4)";
            String sk = "select pj.id from t_biz_pj pj left join t_biz_sfk sfk on sfk.id = pj.sfk_id where sfk.id = ? and sfk.sfklx in (3,4) and pj.status in (2,3,6)";
            if(existsSQLQuery(sk,sfkId)){ //应收款验证 票据状态 1.无状态  2.已贴现 3.已托收  4承兑  5已使用 6已兑换
                throw new RuntimeException("该收款所对应的应收票据已经背书、贴现或托收,不得取消审核！");
            }
            if(existsSQLQuery(fk,sfkId)){ //应付款验证 票据状态 1.无状态  2.已贴现 3.已托收  4承兑  5已使用 6已兑换
                throw new RuntimeException("该付款所对应的应付票据已经承兑或已经兑换,不得取消审核！");
            }
        }

        String sql5 = "select id from t_biz_xyz where sfk_id = ?";
        if(existsSQLQuery(sql5,sfkId)){
            String sk = "select id from t_biz_xyz xyz where xyz.xyzsflx = 0 and xyz.status in (3,4) and xyz.sfk_id = ?";
            String fk = "select id from t_biz_xyz xyz where xyz.xyzsflx = 1 and xyz.status in (2,4) and xyz.sfk_id = ?";
            if(existsSQLQuery(sk,sfkId)){
                throw new RuntimeException("该收款所对应的应收信用证已经变现或已经使用,不得取消审核！");
            }
            if(existsSQLQuery(fk,sfkId)){
                throw new RuntimeException("该付款所对应的应付信用证已经还款或已经使用,不得取消审核！");
            }
        }
        return true;
    }
}
